using System;
using System.ComponentModel;
using System.IO.Packaging;
using System.Xml;
using System.Workflow.ComponentModel;
using System.IO;

namespace OWA.Activities
{
	public class EmbedCustomXmlActivity
        : AbstractCustomXmlActivity
	{
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            Package package = GetPackage();
            Guid storeItemID = StoreItemID;
            XmlDocument customXml = CustomXml;
            PackagePart customXmlPart = GetCustomXmlPart(package, storeItemID);
            if (customXmlPart == null)
            {
                customXmlPart = CreateCustomXmlPart(package, storeItemID);
            }
            StoreCustomXmlData(customXmlPart, customXml);
            return ActivityExecutionStatus.Closed;
        }

        PackagePart CreateCustomXmlPart(Package package, Guid storeItemID)
        {
            Uri customXmlPartUri = CreatePartUri(package, "customXml/item.xml");
            PackagePart mainPart = GetMainPart(package);
            PackagePart customXmlPart = package.CreatePart(customXmlPartUri, "application/xml");
            mainPart.CreateRelationship(customXmlPartUri, TargetMode.Internal, RT_CustomXml);
            Uri customXmlPropertiesUri = CreatePartUri(package, "customXml/itemprops.xml");
            PackagePart propertiesPart = package.CreatePart(customXmlPropertiesUri, "application/xml");
            customXmlPart.CreateRelationship(customXmlPropertiesUri, TargetMode.Internal, RT_CustomXmlProperties);
            using(XmlWriter writer = XmlWriter.Create(
                propertiesPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
            {
                writer.WriteStartDocument(false);
                writer.WriteStartElement("ds", "datastoreItem", XMLNS_Datastore);
                writer.WriteAttributeString("ds", "itemID", XMLNS_Datastore, storeItemID.ToString("B"));
                writer.WriteEndDocument();                
            }
            return customXmlPart;
        }

       

        void StoreCustomXmlData(PackagePart customXmlPart, XmlDocument xmlDocument)
        {
            using (Stream stream = customXmlPart.GetStream(
                FileMode.Create, FileAccess.ReadWrite))
            {
                xmlDocument.Save(stream);
            }
        }
	}
}
